<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://shiro.apache.org/tags" prefix="shiro" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"></c:set>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>数据统计 -- 商品库存</title>
    <link rel="stylesheet" href="${contextPath}/static/statistics/css/bootstrap.min.css">
    <link rel="stylesheet" href="${contextPath}/static/statistics/css/bootstrap-datetimepicker.min.css">
    <link href="${contextPath}/static/ztree/css/zTreeStyle.css" rel="stylesheet"/>
    <script src="${contextPath}/static/statistics/js/jquery.js"></script>
    <script src="${contextPath}/static/statistics/js/bootstrap.min.js"></script>
    <script src="${contextPath}/static/statistics/js/bootstrap-datetimepicker.min.js"></script>
    <script src="${contextPath}/static/statistics/js/bootstrap-datetimepicker.fr.js"></script>
    <script src="${contextPath}/static/statistics/js/bootstrap-datetimepicker.zh-CN.js"></script>
    <script src="${contextPath}/static/statistics/js/bootstrap.min.js"></script>
    <script src="${contextPath}/static/statistics/js/vue.js"></script>
    <script src="${contextPath}/static/statistics/js/echarts.min.js"></script>
    <script type="text/javascript" src="${contextPath}/static/statistics/js/jquery.mockjax.js"></script>
    <script type="text/javascript" src="${contextPath}/static/statistics/js/jquery.autocomplete.js"></script>
    <script type="text/javascript" src="${contextPath}/static/ztree/js/jquery.ztree.core-3.5.js"></script>
    <script type="text/javascript" src="${contextPath}/static/ztree/js/jquery.ztree.excheck-3.5.js"></script>
    <link rel="stylesheet" href="${contextPath}/static/layer/css/layui.css">
    <style>
        .autocomplete-suggestions {
            border: 1px solid #999;
            background: #FFF;
            overflow: auto;
        }

        .autocomplete-suggestion {
            padding: 2px 5px;
            white-space: nowrap;
            overflow: hidden;
        }

        .autocomplete-selected {
            background: #F0F0F0;
        }

        .autocomplete-suggestions strong {
            font-weight: normal;
            color: #3399FF;
        }

        .myh4 {
            margin-top: 10px;
            margin-bottom: 10px;
            font-family: inherit;
            font-weight: 500;
            line-height: 1.1;
            color: inherit;
            font-size: 18px;
        }
    </style>
</head>
<body style="background: rgba(119, 118, 118, 0.15);">
<button style="position: absolute; top: 5px;right: 220px;z-index: 2;"
        type="button" class="btn btn-info" onclick="javascript:window.history.go(-2);window.close();">返回</button>
<div class="container-fluid">
    <div class="row">
        <h4 class="col-sm-6 col-xs-5 myh4">商品库存数据：</h4>
        <div class="spinner col-sm-6 col-xs-7" style="text-align: right; margin-top: 10px">
            <span style="color: green;" class="hide" id="dataTimeId">截止至：2017-01-01 12:12:12</span>
        </div>
    </div>
    <form class="form-inline">
        <shiro:hasPermission name="CLOUDERPORDERSPLADMINORDER:STATISTICS">
            <div class="form-group">
                <input id="quXianNameInput" onfocus="this.value=''" class="form-control input-sm" type="text" placeholder="区县名称">
            </div>
        </shiro:hasPermission>

        <shiro:lacksPermission name="CLOUDERPORDERSPLEMPORDER:STATISTICS">
            <shiro:lacksPermission name="CLOUDERPORDERSPLCHANNELORDER:STATISTICS">
                <div class="form-group">
                    <input id="channelNameId" onfocus="this.value=''" class="form-control input-sm" type="text" placeholder="渠道名称">
                </div>
            </shiro:lacksPermission>
        </shiro:lacksPermission>

        <div class="form-group">
            <input id="custCode" onfocus="this.value=''" class="form-control input-sm" type="text" placeholder="客户编号">
        </div>

        <div class="form-group">
            <input id="shopNameId" onfocus="this.value=''" class="form-control input-sm" type="text" placeholder="店铺名称">
        </div>
        <div class="form-group">
            <input id="orderLevelInput" onfocus="this.value=''"  class="form-control input-sm" type="text" placeholder="档位名称">
        </div>
        <div class="form-group">
            <select class="form-control input-sm" id="isExp">
                <option value="-1">--是否试点--</option>
                <option value="1">是</option>
                <option value="0">否</option>
            </select>
        </div>
        <div class="form-group">
            <select class="form-control input-sm" id="shoptype">
                <option value="0">商品类型</option>
                <option value="05" selected="selected">卷烟</option>
                <option value="03">休闲食品</option>
                <option value="04">粮油</option>
                <option value="06">日配（冷冻、冷藏）</option>
                <option value="07">冲饮</option>
                <option value="08">鲜食及自制饮品</option>
                <option value="09">进口商品</option>
                <option value="10">个人清洁</option>
                <option value="11">家用清洁</option>
                <option value="12">家庭消耗品</option>
                <option value="13">百货、纺织类及小家电</option>
                <option value="14">兑换品耗材及服务项目</option>
                <option value="15">特殊商品</option>
                <option value="16">烟具及烟嘴</option>
                <option value="01">酒</option>
                <option value="02">饮料及常温液态奶制品</option>
            </select>
        </div>
        <div class="form-group input-group">
            <input id="prodNameInput" class="form-control input-sm" readonly type="text" placeholder="未选择商品">
            <span class="input-group-btn">
				<button type="button" class="btn btn-default btn-sm" title="选择商品作为查询条件"
                        onclick="javascript:$('#gridSystemModal').modal('show');">选择</button>
			</span>
        </div>

        <button type="button" class="btn btn-success btn-sm" onclick="selectScratchoff(1);">查询</button>
        <button type="button" class="btn  btn-info btn-sm" onclick="exportExcel();">导出Excel</button>
    </form>

    <div class="table-responsive" id="tableContainer" style="margin-top: 10px;overflow-y: auto;font-size: 18px;">
        <table class="table table-striped table-condensed" id="app">
            <thead style="background-color: #0c3166">
            <tr style="color: rgb(248, 248, 248);">
                <%--<th>序号</th>--%>
                <th>渠道名称</th>
                <th>店铺名称</th>
                <th>客户名称</th>
                <th>商品名称</th>
                <th>商品类型</th>
                <th>商品条码</th>
                <th>商品单位</th>
                <th>库存数量</th>
                <th>库存金额</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="(order,index) in orderList">
                <%--<td>{{index+1}}</td>--%>
                <td>{{order.channelName}}</td>
                <td>{{order.shopName}}</td>
                <td>{{order.custName}}</td>
                <td>{{order.productName}}</td>
                <td>{{order.prodType}}</td>
                <td>{{order.barCode}}</td>
                <td>{{order.unit}}</td>
                <td>{{order.stock}}</td>
                <td>{{(order.totalPrice == 0 || order.totalPrice == null) ? '-' : order.totalPrice }}</td>
            </tr>
            </tbody>
        </table>
    </div>
    <div style="text-align: right;" id="pageDiv"></div>
    <div class="row">
        <div class="col-sm-12 col-xs-12 col-md-6 col-lg-6 main" id="main1" style="margin-top: 10px;"></div>
        <div class="col-sm-12 col-xs-12 col-md-6 col-lg-6 main" id="main2" style="margin-top: 10px;"></div>
    </div>
</div>

<form action="${contextPath}/page/exportExcel" method="post" id="exportExcel" style="display:none">
    <input type="hidden" id="exportExcelData-quXianName" name="stringMap['quXianName']">
    <input type="hidden" id="exportExcelData-channelName" name="stringMap['channelName']">
    <input type="hidden" id="exportExcelData-shopName" name="stringMap['shopName']">
    <input type="hidden" id="exportExcelData-shoptype" name="stringMap['shopType']">
    <input type="hidden" id="exportExcelData-isExp" name="stringMap['isExp']">
    <input type="hidden" id="exportExcelData-orderLevel" name="stringMap['orderLevel']">
    <input type="hidden" id="exportExcelData-productCode" name="stringMap['productCode']">
    <input type="hidden" name="tableType" value="stock">
</form>

<div class="modal fade" tabindex="-1" role="dialog" id="gridSystemModal" aria-labelledby="gridSystemModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="gridSystemModalLabel">选择商品</h4>
            </div>
            <div class="modal-body">
                <div class="content_wrap">
                    <div class="zTreeDemoBackground left">
                        <ul id="treeDemo" class="ztree"></ul>
                    </div>

                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="selectProductTreeNames();">确认</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</body>
<script src=${contextPath}/static/layer/layui.all.js></script>
<script type="text/javascript">
    var laypage = layui.laypage
        , layer = layui.layer;


    var app = new Vue({
        el: '#app',
        data: {
            orderList: [],
            productCode: "",
            page: 1,
        }
    });


    $(".main").height($(window).height() * 0.55)
    //$("#main1").width($(window).width()*0.3333);
    var myChart1 = echarts.init($("#main1")[0])
    var myChart2 = echarts.init($("#main2")[0])
    /*  var myChart3 =  echarts.init($("#main3")[0])*/
    myChart1.on('click', function (param) {
        var name = param.name;
        if (selectOption(name)) {
            selectScratchoff(1)
        }
    })
    myChart2.on('click', function (param) {
        var name = param.name;
        if (selectOption(name)) {
            selectScratchoff(1)
        }
    })
    var option = {
        title: {
            text: '库存数量',
            x: 'center'
        },
        tooltip: {
            trigger: 'item',
            formatter: "{a} <br/>{b} ({d}%)"
        },
        legend: {
            orient: 'vertical',
            left: 'left',
            data: []
        },
        series: [
            {
                name: '库存金额',
                type: 'pie',
                radius: '55%',
                center: ['50%', '60%'],
                data: [],
                itemStyle: {
                    emphasis: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }
        ]
    };
    // 使用刚指定的配置项和数据显示图表。
    myChart1.setOption(option)
    myChart2.setOption(option)
    /*myChart3.setOption(option)*/

    var changeData = function (orderArray) {
        app.orderList.unshift(orderArray)
    }

    var selectShopName = null;

    var countNum = 1;
    var intervalGetOrder = function () {
        //console.log('第' + (countNum++) + '次获取数据')
        $.ajax({
            url: '${contextPath}/page/getStockStatistics', //localhost:8080
            type: 'post',
            data: {
                shopName: selectShopName
            },
            success: function (data) {
                if (data.success) {
                    var dataArray = data.data;


                    //console.log(data.data.SPLOrderDayData)
                    var stockNames = dataArray.stockNames;
                    var priceNamesPriceNamess = dataArray.priceNames;
                    var stockValuess = dataArray.stockValues;
                    var priceValuess = dataArray.priceValues;


                    updateOrderDayData(stockNames, stockValuess)
                    updateOrderMonthData(priceNamesPriceNamess, priceValuess)
                    /*updateOrderYearData(SPLOrderYearDataObj)*/

                } else if (data.success == undefined) {
                    window.location.href = "${contextPath}"
                }
                //console.log(data.data)
            },
            error: function (error) {
                //console.log(error)
            }
        })
    }
    var intervalId;
    intervalId = setInterval(intervalGetOrder, "10000");

    $("#tableContainer").css("border", "1px solid gray");
    //改变div的高度
    $("#tableContainer").height($(window).height() * 0.35);

    function updateOrderDayData(names, values) {
        myChart1.setOption({
            title: {
                text: '库存数量统计'
            },
            legend: {
                orient: 'vertical',
                left: 'left',
                data: names
            },
            series: [
                {
                    name: '库存数量',
                    type: 'pie',
                    radius: '55%',
                    center: ['50%', '60%'],
                    data: values,
                    itemStyle: {
                        emphasis: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        });

    }

    function updateOrderMonthData(names, values) {
        myChart2.setOption({
            title: {
                text: '库存金额统计'
            },
            legend: {
                orient: 'vertical',
                left: 'left',
                data: names
            },
            series: [
                {
                    name: '库存金额',
                    type: 'pie',
                    radius: '55%',
                    center: ['50%', '60%'],
                    data: values,
                    itemStyle: {
                        emphasis: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        });

    }

    /*function updateOrderYearData(data) {
     myChart3.setOption({
     title: {
     text: '当周中奖统计'
     },
     legend: {
     orient: 'vertical',
     left: 'left',
     data: data.names
     },
     series : [
     {
     name: '中奖数据',
     type: 'pie',
     radius : '55%',
     center: ['50%', '60%'],
     data:data.data,
     itemStyle: {
     emphasis: {
     shadowBlur: 10,
     shadowOffsetX: 0,
     shadowColor: 'rgba(0, 0, 0, 0.5)'
     }
     }
     }
     ]
     });

     }*/
    intervalGetOrder()


    var selectScratchoff = function (page) {
        var quXianName = $("#quXianNameInput").val();
        var channelName = $("#channelNameId").val();
        var shopName = $("#shopNameId").val();
        var shoptype = $("#shoptype").val();
        var isExp = $("#isExp").val();
        var orderLevel = $("#orderLevelInput").val();
        var custCode = $("#custCode").val();
        if (quXianName == "" && shopName == "" && shoptype == "" && channelName == "" && app.productCode == "" && orderLevel == "") {
            layer.msg("请至少选择除试点店以外的一个查询条件")
            return
        }
        layer.load(1);
        app.page = page;
        $.ajax({
            url: '${contextPath}/page/selectStock',
            type: 'post',
            dataType: 'json',
            data: {
                stringMap: {
                    page: page,
                    quXianName: quXianName,
                    shopName: shopName,
                    shopType: shoptype,
                    channelName: channelName,
                    custCode: custCode,
                    productCode: app.productCode,
                    isExp: isExp,
                    orderLevel: orderLevel,
                },

            },
            success: function (data) {
                if (data.success) {
                    var arrayObj = data.data;
                    var array = arrayObj.recordList;
                    if (array.length > 0) {
                        //  clearInterval(intervalId)

                        /* var numTotal = {};
                         numTotal.shopName = "合计："
                         var stock = 0;
                         var totalPrice = 0;
                         for (index in  array) {
                             //console.log(array)
                             stock = numAdd(array[index].stock, stock);
                             totalPrice = numAdd(array[index].totalPrice, totalPrice);
                         }
                         numTotal.stock = stock
                         numTotal.totalPrice = totalPrice
                         array.unshift(numTotal)*/

                        app.orderList = array
                        //$(".spinner").addClass("hide")
                        var date = new Date();
                        var time = "截止至：" + date.getFullYear() + "-" + formatDate(date.getMonth() + 1) + "-" + formatDate(date.getDate()) + " " + formatDate(date.getHours()) + ":" + formatDate(date.getMinutes()) + ":" + formatDate(date.getSeconds());


                        $("#dataTimeId").html(time);
                        $("#dataTimeId").removeClass("hide");

                        selectShopName = $("#shopNameId").val();
                        intervalGetOrder();


                        laypage({
                            cont: 'pageDiv'
                            , pages: arrayObj.pageCount //总页数
                            , groups: 5 //连续显示分页数
                            , curr: arrayObj.currentPage
                            , skin: '#1E9FFF',
                            jump: function (obj, first) {
                                var curr = obj.curr;
                                if (!first) {
                                    selectScratchoff(curr)
                                }
                            }
                        });

                    } else {
                        layer.msg("所选条件没有数据")
                    }
                } else {
                    layer.msg(data.message);
                }
                layer.closeAll('loading')
            },
            error: function (error) {
                layer.msg("网络连接失败")
                //console.log(error)
                layer.closeAll('loading')
            }
        })
    }

    var exportExcel = function () {

        var quXianName = $("#quXianNameInput").val();
        var channelName = $("#channelNameId").val();
        var shopName = $("#shopNameId").val();
        var shoptype = $("#shoptype").val();
        var isExp = $("#isExp").val();
        var orderLevel = $("#orderLevelInput").val();
        var custCode = $("#custCode").val();

        $('#exportExcelData-quXianName').val(quXianName);
        $('#exportExcelData-channelName').val(channelName);
        $('#exportExcelData-shopName').val(shopName);
        $('#exportExcelData-shoptype').val(shoptype);
        $('#exportExcelData-isExp').val(isExp);
        $('#exportExcelData-orderLevel').val(orderLevel);
        $('#exportExcelData-custCode').val(custCode);
        $('#exportExcelData-productCode').val(app.productCode);

        $("#exportExcel").submit();

    }

    var getShopNameToSelect = function (channelName) {
        $.ajax({
            url: '${contextPath}/page/getShopNameToSelect?channelName=' + channelName,
            success: function (data) {
                if (data.success) {
                    var countries = data.data
                    $('#shopNameId').autocomplete({
                        lookup: countries,
                        onSelect: function (suggestion) {
                            // alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
                        },
                        minChars: 0,
                    });
                }
            }
        })
    }
    getShopNameToSelect('')

    var selectChannelNameToSelected = function (quXianName) {
        $.ajax({
            url: '${contextPath}/checking/selectChannelNameToSelected?quXianName=' + quXianName,
            success: function (data) {
                if (data.success) {
                    var countries = data.data
                    $('#channelNameId').autocomplete({
                        lookup: countries,
                        onSelect: function (suggestion) {
                            // alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
                            getShopNameToSelect(suggestion.value)
                        },
                        width: 200,
                        minChars: 0,
                    });
                }
            }
        })
    }
    selectChannelNameToSelected('')


    $.ajax({
        url: '${contextPath}/checking/selectQuXianNameToSelected',
        success: function (data) {
            if (data.success) {
                var countries = data.data
                $('#quXianNameInput').autocomplete({
                    lookup: countries,
                    onSelect: function (suggestion) {
                        // alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
                        selectChannelNameToSelected(suggestion.value)
                    },
                    width: 200,
                    minChars: 0,
                });
            }
        }
    })

    var formatDate = function (data) {
        if (data < 10) {
            data = "0" + data
        }
        return data
    }

    var selectOption = function (name) {
        var realName = name.substring(0, name.indexOf("："));
        var index = null;
        switch (realName) {
            case '烟' :
                index = 1
                break;
            case '酒' :
                index = 2
                break;
            case '饮料、水' :
                index = 3
                break;
            case '食品' :
                index = 4
                break;
            case '生活用品' :
                index = 5
                break;
            case '其它' :
                index = 6
                break;
            case '未归类' :
                index = -1
                break;
            default :
                break;
        }
        var idx = $("#shoptype").val()
        if (index == null || index == idx) {
            return false
        }
        /*     $("#shoptype").find("option").attr("selected",false);
         $("#shoptype").find("option:eq("+index+")").attr("selected",'selected');*/
        $("#shoptype").val(index)

        return true

    }

    function numAdd(num1, num2) {
        if (num1 == null || num1 == undefined || num1 == "") {
            return num2;
        }
        var baseNum, baseNum1, baseNum2;
        try {
            baseNum1 = num1.toString().split(".")[1].length;
        } catch (e) {
            baseNum1 = 0;
        }
        try {
            baseNum2 = num2.toString().split(".")[1].length;
        } catch (e) {
            baseNum2 = 0;
        }
        baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
        var precision = (baseNum1 >= baseNum2) ? baseNum1 : baseNum2;//精度
        return ((num1 * baseNum + num2 * baseNum) / baseNum).toFixed(precision);
        ;
    };

    if (selectOption('烟：')) {
        selectScratchoff(1)
    }

    $.ajax({
        url: '${contextPath}/page/getProductThreeName',
        success: function (data) {
            if (data.success) {
                var zNodes = data.data;

                var setting = {
                    check: {
                        enable: true,
                        chkStyle: "checkbox",
                    },

                    data: {
                        simpleData: {
                            enable: true,
                            idKey: "ID",
                            pIdKey: "PID",
                            rootPId: '0',
                        },
                        key: {
                            name: "NAME"
                        },
                    },
                };

                $.fn.zTree.init($("#treeDemo"), setting, zNodes);
            }
        }
    })

    var selectProductTreeNames = function () {
        $("#gridSystemModal").modal('hide')
        var zTree = $.fn.zTree.getZTreeObj("treeDemo");
        var nodes = zTree.getCheckedNodes();
        app.productCode = ""
        if (nodes.length == 0) {
            $("#prodNameInput").val("")
            return
        }
        var length = 0;
        for (var index in nodes) {
            var node = nodes[index]
            if (node.ISPRODNAME) {
                app.productCode = "'" + node.ID + "'," + app.productCode
                length++;
            }
        }
        app.productCode = app.productCode.substr(0, app.productCode.length - 1)
        $("#prodNameInput").val("已选择" + length + "条商品")
    }
    var selectOrderLevelToSelected = function () {
        $.ajax({
            url: '${contextPath}/checking/selectOrderLevelToSelected',
            success: function (data) {
                if (data.success) {
                    var countries = data.data
                    $('#orderLevelInput').autocomplete({
                        lookup: countries,
                        onSelect: function (suggestion) {
                            //console.log('You selected: ' + suggestion.value + ', ' + suggestion.data);
                        },
                        //width: 200,
                        minChars: 0,
                    });
                }
            }
        })
    };
    selectOrderLevelToSelected();

    //******************* 表头固定 *********************
    // Code goes here
    'use strict'
    window.onload = function(){
        var tableCont = document.querySelector('#tableContainer')
        /**
         * scroll handle
         * @param {event} e -- scroll event
         */
        function scrollHandle (e){
            console.log(this)
            var scrollTop = this.scrollTop;
            this.querySelector('thead').style.transform = 'translateY(' + scrollTop + 'px)';
        }

        tableCont.addEventListener('scroll',scrollHandle)
    }

    //****************************************
    $("#shoptype").val('05');
</script>
</html>





